package com.gexiaobao.pigeon.ui.fragment.mine.organization.detail

import android.animation.ObjectAnimator
import android.content.res.ColorStateList
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.fragment.app.setFragmentResultListener
import androidx.lifecycle.ViewModelProvider
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.ext.Constant
import com.gexiaobao.pigeon.app.ext.showMessage
import com.gexiaobao.pigeon.app.model.bean.OrgInfoDetailResponse
import com.gexiaobao.pigeon.app.model.bean.VisitMemberListResponse
import com.gexiaobao.pigeon.app.network.HttpUtil
import com.gexiaobao.pigeon.app.util.CacheUtil
import com.gexiaobao.pigeon.app.util.KvUtils
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.databinding.FragmentOrgCompetitionBinding
import com.gexiaobao.pigeon.ui.activity.ActivityRaceRanking
import com.gexiaobao.pigeon.ui.dialog.RxDialogMemberList
import com.gexiaobao.pigeon.ui.fragment.mine.organization.FragmentPigeonShedInfo
import com.gexiaobao.pigeon.ui.fragment.mine.organization.activity.ActivityDeliveringThePigeons
import com.gexiaobao.pigeon.ui.fragment.mine.organization.activity.ActivityGroupNow
import com.gexiaobao.pigeon.ui.fragment.mine.organization.activity.ActivityLiveLevelContent
import com.gexiaobao.pigeon.ui.fragment.mine.organization.activity.ActivityMakeAnAppointment
import com.gexiaobao.pigeon.ui.fragment.mine.organization.activity.ActivityMyVisitVideo
import com.gexiaobao.pigeon.ui.fragment.mine.organization.activity.ActivityOrgTentPicture
import com.gexiaobao.pigeon.ui.fragment.mine.organization.activity.ActivityReserveDetail
import com.gexiaobao.pigeon.ui.fragment.mine.organization.activity.ActivityVisitByAppointment
import com.gexiaobao.pigeon.ui.fragment.mine.organization.activity.ActivityWatchRegistration
import com.gexiaobao.pigeon.viewmodel.OrgDetailViewModel
import com.gexiaobao.pigeon.viewmodel.SharedViewModel
import com.google.android.material.tabs.TabLayout
import com.google.gson.Gson
import com.luck.picture.lib.thread.PictureThreadUtils
import com.xinbida.wukongim.entity.WKChannelType
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.startActivity
import me.hgj.jetpackmvvm.util.startActivityForResult
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONException
import org.json.JSONObject


/**
 * @Author      : hxw
 * @Date        : 2024/5/23 13:51
 * @Describe    : 公棚-赛事
 */
class FragmentOrgCompetition : BaseFragment<OrgDetailViewModel, FragmentOrgCompetitionBinding>() {

    private var isExpanded = false
    private var mState: Int = 0//1-审核中 2-审核通过 3-审核失败
    private var mOrgId: Int = 0
    private var mRaceId = 0
    private var memberId = 0
    private var mBaseId = 0
    private var mMemberName = ""
    private var mRaceName = ""
    private var mOrgIcon = ""
    private var isEmptyList = false
    private var isVisitState = false//是否开启了预约探视通道
    private var isOpenReservation = 0//是否开启了预约会员通道
    private var memberList: ArrayList<VisitMemberListResponse.ListBean> = arrayListOf()
    private var intentType = ""
    private var goType = ""
    private var uid = ""
    private var channelID = ""
    private var token = ""

    private var viewModel: SharedViewModel? = null

    interface OnDataSendListener {
        fun onMessageSent(data: OrgInfoDetailResponse)
    }

    private var mListener: OnDataSendListener? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        viewModel = ViewModelProvider(requireActivity())[SharedViewModel::class.java]
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    override fun initView(savedInstanceState: Bundle?) {
        uid = KvUtils.decodeString(Constant.USERID)
        token = CacheUtil.getToken()
        goType = requireArguments().getString("type").toString()
        mOrgId = requireArguments().getInt("orgId", 0)
        mRaceId = requireArguments().getInt("raceId", 0)
        mRaceName = requireArguments().getString("raceName").toString()

        showLoading(getString(R.string.loading))
        mViewModel.orgInfoToApp(mOrgId.toString())
        channelID = if (mOrgId == 0) "" else mOrgId.toString()
        chatLogin(channelID)

        initTabLayout()
        mDatabind.sRefreshRace.setOnRefreshListener {
            mViewModel.getOrgRaceInfoState(mRaceId, mOrgId, goType)
        }

        parentFragment?.setFragmentResultListener("rCHistoryRace") { _, bundle ->
            mRaceName = bundle.getString("raceName").toString()
            eventViewModel.toNotifyRaceName.value = mRaceName
            mRaceId = bundle.getInt("raceId")
            goType = "race"
            showLoading(getString(R.string.loading))
            mViewModel.getOrgRaceInfoState(mRaceId, mOrgId, goType)
        }
    }

    private fun setAppointmentType(isOpen: Int) {
        isOpenReservation = isOpen
        mDatabind.tvAppointmentIsOpen.isVisible = true
        if (isOpen == 2) {
            mDatabind.tvAppointmentIsOpen.text = getString(R.string.not_open)
            mDatabind.tvAppointmentIsOpen.background = ContextCompat.getDrawable(requireContext(), R.drawable.round_btn_light_gray15_b_g)
        } else {
            mDatabind.tvAppointmentIsOpen.text = getString(R.string.opened)
            mDatabind.tvAppointmentIsOpen.background = ContextCompat.getDrawable(requireContext(), R.drawable.round_btn_red25_b_g)
        }
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.createChannelResult.observe(viewLifecycleOwner) {
            dismissLoading()
            startActivity<ActivityLiveLevelContent>(
                "raceName" to mRaceName,
                "orgId" to mOrgId,
                "channelId" to channelID,
                "token" to token,
                "uid" to uid,
                "raceId" to mRaceId
            )
        }

        /** 获取公棚详情信息 */
        mViewModel.orgInfoDetailResult.observe(viewLifecycleOwner) {
            if (it != null) {
                if (parentFragment is OnDataSendListener) {
                    mListener = parentFragment as OnDataSendListener?
                }

                if (mListener != null) {
                    mListener!!.onMessageSent(it)
                }
            }
            mMemberName = it.orgName
            mOrgIcon = it.icon
            if (goType == "org") {
                mRaceId = it.raceId
                mRaceName = it.raceName
            }
            showLoading(getString(R.string.loading))
            mViewModel.getOrgRaceInfoState(mRaceId, mOrgId, goType)
            // 发送数据到父 Fragment
            val parentFragment = parentFragment as? FragmentPigeonShedInfo
            parentFragment?.passDataToChildFragment(it)
        }
        /** 获取赛事信息 */
        mViewModel.raceInfoResult.observe(viewLifecycleOwner) {
            /** 通知刷新 关卡列表 */
            viewModel?.setRaceInfoData(it)
            /** 通知刷新 接鸽清单 */
            val data = OrgInfoDetailResponse()
            data.raceId = mRaceId
            data.orgName = it.orgName
            data.raceName = it.raceName
            data.icon = mOrgIcon
            viewModel!!.setOrgInfoBean(data)
            /** 渲染页面状态 */
            setAppointmentType(it.state)
            isVisitState = it.VisitState
            setVisitIsOpen(isVisitState)
            dismissLoading()
        }
        /** 获取单用户下探视棚号列表  */
        mViewModel.visitMemberResult.observe(this) {
            cancelRefresh()
            isEmptyList = it.list.isEmpty()
            if (it.list.size == 1) {
                memberId = it.list[0].memberId
            } else {
                memberList.clear()
                memberList.addAll(it.list)
            }
            viewModel?.setMemberInfoListData(it.list)
        }
        /** 获取会员预定详情 */
        mViewModel.memberReservationResult.observe(this) {
            cancelRefresh()
            if (it != null) {
                mState = it.state
            }
        }
    }

    private fun chatLogin(channelID: String) {
        if (!TextUtils.isEmpty(uid) && !TextUtils.isEmpty(token)) {
            val jsonObject = JSONObject()
            try {
                jsonObject.put("uid", uid)
                jsonObject.put("token", token)
                jsonObject.put("device_flag", 0)
                jsonObject.put("device_level", 1)
            } catch (e: JSONException) {
                throw RuntimeException(e)
            }
            Thread {
                HttpUtil.getInstance().post("/user/token", jsonObject) { code, _ ->
                    if (code == 200) {
                    } else {
                        PictureThreadUtils.runOnUiThread {
                            RxToast.showToast("登录失败【$code】")
                        }
                    }
                }
            }.start()
        }
    }

    private fun cancelRefresh() {
        if (mDatabind.sRefreshRace.isRefreshing) {
            mDatabind.sRefreshRace.isRefreshing = false
        }
    }

    private fun setVisitIsOpen(visitState: Boolean) {
        mDatabind.tvVisitIsOpen.isVisible = true
        if (visitState) {
            mDatabind.tvVisitIsOpen.text = getString(R.string.study_in_finland)
            mDatabind.tvVisitIsOpen.background = ContextCompat.getDrawable(requireContext(), R.drawable.round_btn_red25_b_g)
        } else {
            mDatabind.tvVisitIsOpen.text = getString(R.string.not_open)
            mDatabind.tvVisitIsOpen.background = ContextCompat.getDrawable(requireContext(), R.drawable.round_btn_light_gray15_b_g)
        }
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.llMakeAnAppointment,
            mDatabind.llOrgInfoMore,
            mDatabind.llVisit,
            mDatabind.llSignUp,
            mDatabind.llTentPic,
            mDatabind.llVisitVideo,
            mDatabind.llPigeonDelivery,
            mDatabind.llIntegratedRanking,
            mDatabind.llGroupGrouping,
            mDatabind.llLive
        ) { it ->
            when (it) {
                mDatabind.llLive -> createChannelAndSubscriber()
                mDatabind.llGroupGrouping -> {
                    intentType = "groupSign"
                    appointmentVisit()
                }

                mDatabind.llIntegratedRanking -> {
                    startActivity<ActivityRaceRanking>("title" to mRaceName, "raceId" to mRaceId)
                    activity?.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
                }

                mDatabind.llPigeonDelivery -> {
                    if (isEmptyList) {
                        RxToast.warning(getString(R.string.Please_book_and_become_a_member_before_you_deliver_your_pigeons))
                        return@setOnclickNoRepeat
                    }
                    startActivity<ActivityDeliveringThePigeons>("orgId" to mOrgId, "raceId" to mRaceId)
                }

                mDatabind.llVisitVideo -> startActivity<ActivityMyVisitVideo>("raceId" to mRaceId)
                mDatabind.llTentPic -> startActivity<ActivityOrgTentPicture>("raceId" to mRaceId, "orgId" to mOrgId)//入棚照片


                mDatabind.llSignUp -> {//关赛报名
                    intentType = "passSign"
                    appointmentVisit()
                }

                mDatabind.llVisit -> {//预约探视
                    intentType = "visit"
                    appointmentVisit()
                }

                mDatabind.llMakeAnAppointment -> {//预约通道
                    if (isOpenReservation == 2) {
                        showMessage(getString(R.string.not_open_for_member_booking))
                        return@setOnclickNoRepeat
                    }
                    if (mState == 2) {
                        startActivity<ActivityReserveDetail>(
                            "raceId" to mRaceId,
                            "memberName" to mMemberName,
                            "raceName" to mRaceName,
                            "orgIcon" to mOrgIcon,
                        )
                    } else {
                        startActivityForResult<ActivityMakeAnAppointment>(
                            "raceId" to mRaceId,
                            "memberName" to mMemberName,
                            "raceName" to mRaceName,
                            "orgIcon" to mOrgIcon,
                        ) {
                            if (it != null) {
                                if (it.getBooleanExtra("isRefresh", false)) {
                                    /** 获取会员预定详情 */
                                    mViewModel.getMemberReservation(mRaceId.toString())
                                }
                            }
                        }
                    }
                }

                mDatabind.llOrgInfoMore -> {
                    mDatabind.expandLayout.setExpanded(!isExpanded, true)
                    mDatabind.expandLayout.duration = 500
                    if (isExpanded) {
                        mDatabind.tvOrgInfoMore.text = getString(R.string.read_more)
                        val rotateAnim: ObjectAnimator = ObjectAnimator.ofFloat(mDatabind.ivOrgInfoMore, "rotation", 180.0f, 0.0f)
                        rotateAnim.setDuration(500)
                        rotateAnim.start()
                    } else {
                        mDatabind.tvOrgInfoMore.text = getString(R.string.pack_up)
                        val rotateAnim: ObjectAnimator = ObjectAnimator.ofFloat(mDatabind.ivOrgInfoMore, "rotation", 0.0f, 180.0f)
                        rotateAnim.setDuration(500)
                        rotateAnim.start()
                    }
                    isExpanded = !isExpanded
                }
            }
        }
    }

    private fun createChannelAndSubscriber() {
        val mSubscribers1 = arrayOf<String>()
        val map1 = mapOf(
            "channel_id" to mOrgId.toString(),
            "channel_type" to WKChannelType.GROUP,
            "ban" to 0,
            "subscribers" to mSubscribers1,
        )
        val body1: RequestBody = Gson().toJson(map1).toRequestBody("application/json".toMediaTypeOrNull())
        val mSubscribers2 = arrayOf(uid)
        val map2 = mapOf(
            "channel_id" to mOrgId.toString(),
            "channel_type" to WKChannelType.GROUP,
            "reset" to 0,//是否重置订阅者 （0.不重置 1.重置），选择重置，则删除旧的订阅者，选择不重置则保留旧的订阅者
            "temp_subscriber" to 1,//是否为临时频道 0.否 1.是 临时频道的订阅者将在下次重启后自动删除
            "subscribers" to mSubscribers2,
        )
        showLoading(getString(R.string.loading))
        val body2: RequestBody = Gson().toJson(map2).toRequestBody("application/json".toMediaTypeOrNull())
        mViewModel.createChannelAndSubscriber(body1, body2)
    }

    private fun appointmentVisit() {
        if (isEmptyList) {
            RxToast.warning(getString(R.string.You_have_not_yet_applied_for_this_event_membership))
            return
        }
        if (intentType == "visit") {
            if (!isVisitState) {
                showMessage(getString(R.string.not_open_for_scheduled_visitation))
                return
            }
        }
        if (memberList.size > 1) {
            showMemberDialog()
        } else {
            intentToActivity()
        }
    }

    private fun intentToActivity() {
        when (intentType) {
            "visit" -> startActivity<ActivityVisitByAppointment>("memberId" to memberId, "raceId" to mRaceId)
            "passSign" -> startActivity<ActivityWatchRegistration>(
                "orgName" to mMemberName,
                "raceName" to mRaceName,
                "orgIcon" to mOrgIcon,
                "raceId" to mRaceId,
                "memberId" to memberId
            )

            "groupSign" -> startActivity<ActivityGroupNow>(
                "memberId" to memberId,
                "raceId" to mRaceId,
                "orgName" to mMemberName,
                "raceName" to mRaceName,
                "orgIcon" to mOrgIcon,
                "baseId" to mBaseId
            )
        }
    }

    private fun showMemberDialog() {
        val dialog = RxDialogMemberList(context)
        dialog.setAdapterData(memberList)
        dialog.setOnClickListener(object : RxDialogMemberList.OnItemClickListener {
            override fun onItemClick(position: Int, id: Int) {
                memberId = id
                intentToActivity()
                dialog.dismiss()
            }
        })
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun initTabLayout() {
        mDatabind.tabLayout.tabRippleColor = ColorStateList.valueOf(ContextCompat.getColor(requireContext(), android.R.color.transparent))
        val tab1 = mDatabind.tabLayout.newTab().setText(getString(R.string.Level_list))
        tab1.setTag("fragmentOrgPassList")
        mDatabind.tabLayout.addTab(tab1)
        val tab2 = mDatabind.tabLayout.newTab().setText(getString(R.string.Pigeon_receipt_list))
        mDatabind.tabLayout.addTab(tab2)

        mDatabind.tabLayout.addOnTabSelectedListener(object : TabLayout.BaseOnTabSelectedListener<TabLayout.Tab> {
            override fun onTabReselected(p0: TabLayout.Tab) {}
            override fun onTabUnselected(p0: TabLayout.Tab) {}

            override fun onTabSelected(p0: TabLayout.Tab) {
                replaceFragments(p0.position)
            }
        })
        replaceFragments(0)
    }

    private fun replaceFragments(position: Int) {
        childFragmentManager.beginTransaction().apply {
            when (position) {
                0 -> replace(R.id.raceContainer, FragmentOrgPass.newInstance())
                1 -> replace(R.id.raceContainer, FragmentPigeonReceipt.newInstance())
            }
        }.commitAllowingStateLoss()
    }

    companion object {

        fun newInstance(raceId: Int, orgId: Int, type: String, raceName: String): FragmentOrgCompetition {
            val fragment = FragmentOrgCompetition()
            val bundle = Bundle()
            bundle.putInt("raceId", raceId)
            bundle.putInt("orgId", orgId)
            bundle.putString("type", type)
            bundle.putString("raceName", raceName)
            fragment.arguments = bundle
            return fragment
        }
    }
}